<template>
  <div>
    <div class="xiaoqu">
      <el-row>
        <el-col :span="6">
          公告标题：<el-input
            style="width: 200px; height: 38px"
            clearable
            v-model="title"
          />
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            style="height: 38px; width: 70px"
            @click="search"
            >搜索</el-button
          >
        </el-col>
      </el-row>
      <el-row class="col" style="margin-top: 20px">
        <el-button type="primary" @click="openInsertDialog()">发布公告</el-button>
      </el-row>
      <el-row class="col" style="margin-top: 20px">
        <el-table
          :data="tongzhiList"
          border
          style="width: 100%; text-align: center"
          :header-cell-style="{
            backgroundColor: '#1890ff',
            color: 'white',
            textAlign: 'center',
            height: '50px',
          }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="img" label="图片">
            <template #default="scope">
              <img
                :src="scope.row.img"
                alt="图片描述"
                style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="context" label="内容" />
          <el-table-column prop="time" label="发布时间">
            <template #default="scope">
              <span>{{ formatTimeStamp(scope.row.time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="text"
                class="text"
                @click="openUpdateDialog(scope.row)"
                >修改公告</el-button
              >
              <el-button
                type="text"
                class="text"
                @click="openDeleteDialog(scope.row)"
                >删除公告</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 定义弹出框 -->
      <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
        <p>确定要删除该公告吗？此操作不可恢复。</p>
        <template #footer>
          <span>
            <el-button @click="cancelDelete">取消</el-button>
            <el-button type="primary" @click="deleteTongZhi()">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="InsertDialogVisible" title="发布公告">
        <TianJia @tongzhiData="handletongzhiData"></TianJia>
        <template #footer>
          <el-button class="text" @click="cancelInsert">取消</el-button>
          <el-button type="primary" @click="InsertUser()">保存</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="UpDateDialogVisible" title="编辑公告">
        <BianJi
          :key="child.id"
          @tongzhirData="handleUsersData"
          :data="child"
        ></BianJi>
        <template #footer>
          <el-button class="text" @click="cancelupdate">取消</el-button>
          <el-button type="primary" @click="updateUser()">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { onMounted,ref } from "vue";
import { ElMessage } from "element-plus";
import BianJi from "./Component/BianJi.vue";
import TianJia from "./Component/TianJia.vue";

const tongzhiList = ref([]);
const id = ref("");
const title = ref("");
const qs = require("qs");
const tongzhis=ref([]);
const tongzhi=ref([]);
const child=ref([]);

const deleteDialogVisible = ref(false);
// 打开删除通知对话框
const openDeleteDialog = (data) => {
  deleteDialogVisible.value = true;
  console.log(data);
  id.value = data.id;
};
// 取消删除操作
const cancelDelete = () => {
  deleteDialogVisible.value = false;
};
// 删除通知
const deleteTongZhi = async () => {
  deleteDialogVisible.value = false;
  console.log(`删除通知：${id.value}`);
  try {
    // 使用await等待axios.post请求完成并获取响应
    await axios.post(
      "http://localhost:8080/shanchu",
      qs.stringify({
        id: id.value,
      })
    );
    // 调用成功，则提示删除成功
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    sou();
  } catch (error) {
    console.error("获取区域数据时出现错误：", error);
  }
};


//从子组件接收数据
const handletongzhiData = (data) => {
  console.log('从子组件接收到的数据：', data);
  tongzhi.value=data;
};
// 新增用户对话框的显示状态
const InsertDialogVisible = ref(false);
// 打开发布公告对话框
const openInsertDialog = () => {
  InsertDialogVisible.value = true;
};
// 取消新增操作
const cancelInsert = () => {
  InsertDialogVisible.value = false;
};
// 新增用户
const InsertUser = async () => {
  InsertDialogVisible.value = false;
  console.log(`新增用户：${tongzhi.value}`);
  try {
    // 使用await等待axios.post请求完成并获取响应
    await axios.post(
      "http://localhost:8080/insert",
      qs.stringify({
        ...tongzhi.value,
      })
    );
    // 调用成功，则提示删除成功
    ElMessage({
      message: "新增成功",
      type: "success",
    });
    sou();
  } catch (error) {
    console.error("获取区域数据时出现错误：", error);
  }
};

//从子组件接收数据
const handleUsersData = (data) => {
  console.log('从子组件接收到的数据：', data);
  tongzhis.value=data;
};
// 编辑用户对话框的显示状态
const UpDateDialogVisible = ref(false);
// 打开编辑用户对话框
const openUpdateDialog = (data) => {
  UpDateDialogVisible.value = true;
  child.value=data;
};
// 取消编辑操作
const cancelupdate = () => {
  UpDateDialogVisible.value = false;
};
// 更新用户
const updateUser = async () => {
  UpDateDialogVisible.value = false;
  console.log(`更新用户：${tongzhis.value}`);
  try {
    await axios.post(
      "http://localhost:8080/bianji",
      qs.stringify({
        ...tongzhis.value,
      })
    );
    // 调用成功，则提示更新成功
    ElMessage({
      message: "更新成功",
      type: "success",
    });
    sou();
  } catch (error) {
    console.error("获取区域数据时出现错误：", error);
  }
};



//模糊查询
const search = async function () {
  console.log(title.value);
  const queryParams = qs.stringify({
    title: title.value
});
  const url = `http://localhost:8080/mohu?${queryParams}`;
 axios.get(url)
    .then((response) => {
      tongzhiList.value = response.data.data;
    })
    .catch((error) => {
      console.error("获取区域数据时出现错误：", error);
    });
};

const formatTimeStamp = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const sou =async function() {
  axios
    .get("http://localhost:8080/tongzhi")
    .then((response) => {
      tongzhiList.value = response.data.data;
    })
    .catch((error) => {
      console.error("获取区域数据时出现错误：", error);
    });
}

onMounted(() => {
  sou();
});
</script>

<style lang="less" scoped>
</style>